<?php
/*
 *   This file is part of poat.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 */

function selectLang() {
	$_AL=strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']);
	
	$_ALS = strtok($_AL, ",");
	$_ASR=array();
	
	while ($_ALS !== false) {
		array_push($_ASR, $_ALS);
	    $_ALS = strtok(",");
	}
	
	$lset=false;
	$llist = loadLanguageList();
	foreach ($_ASR as &$value) {
		$v=strpos($value,";");
		if ($v!='') {
			$_AS = substr($value,0,$v);
		} else {
			$_AS = $value;
		}		
		
		$_AS = str_replace("-","_",$_AS);
	
		if (array_key_exists($_AS,$llist)) {
			updateLang($_AS);
			$lset=true;
			break;
		} elseif(strpos($_AS,"_")!==false) {
			$_AS = substr($_AS,0,strpos($_AS,"_"));
			if (array_key_exists($_AS,$llist)) {
				updateLang($_AS);
				$lset=true;
				break;
			}	
		}
	}
	
	if (!$lset) {
		updateLang(DEFAULT_LANG);
	}
}

function updateLang($lang) {
	global $_log;
	$_log->debug("Set Language: $lang");
	global $LANG;
	$LANG = $lang;
} 

function loadLanguageList() {
	global $loader;
	
	$l = new i18n;
	$list = $loader->fetchlist($l->listAvailLang(),"lang");
	$list["en"]=array("lang"=>"en","name"=>"English");
	asort($list);
	return $list;	
}

function langCacheKey($s,$l) {
	return $l.".".sha1($s);
}

function s($s,$lng=null,$dec=false) {
	global $loader;
	global $LANG;
		
	$ln = $lng == null ? $LANG : $lng;
	$res = $s.'';
		
	if ($ln!="en") {
		$k = langCacheKey($s,$LANG);
		if (check($k)) {
			$res = retrieve($k);
		} else {
			$l = new i18n;
			$r = $loader->getBy($l,$l->find($s,$ln));
			if ($r) {
				cache($k,$l->translated);
				$res = $l->translated;
			}			
		}

	}
	if ($dec) {
		$res = util::decode($res);
	}
	return $res;
}
?>
